/**
 * 160. 相交链表
 * https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
 */
const { createListNode } = require('../../libs/public');

// /**
//  * @param {ListNode} headA
//  * @param {ListNode} headB
//  * @return {ListNode}
//  */
// function getIntersectionNode(headA, headB) {
//   let node = headA;
//   while (node) {
//     node._checked = true;
//     node = node.next;
//   }
//   node = headB;
//   while (node) {
//     if (node._checked) return node;
//     node = node.next;
//   }
//   return null;
// }

/**
 * 指针
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
function getIntersectionNode(headA, headB) {
  let node1 = headA;
  let node2 = headB;
  while (node1 !== node2) {
    node1 = node1 ? node1.next : headB;
    node2 = node2 ? node2.next : headA;
  }
  return node1;
}

let head1;
let head2;

head1 = createListNode([4, 1, 8, 4, 5]);
head2 = createListNode([5, 6, 1]);
head2.next.next.next = head1.next.next;
console.log(getIntersectionNode(head1, head2).val === 8);

head1 = createListNode([1, 9, 1, 2, 4]);
head2 = createListNode([3]);
head2.next = head1.next.next.next;
console.log(getIntersectionNode(head1, head2).val === 2);

head1 = createListNode([2, 6, 4]);
head2 = createListNode([1, 3]);
console.log(getIntersectionNode(head1, head2) === null);
